package com.dev;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.StateListDrawable;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ProgressBar;
import android.app.Application;
import android.view.WindowManager;
public class HtmlEditorTab extends TextView implements TabBar.Tab{
	private OnClickListener ocl;
	private OnLongClickListener olcl;
	private boolean dontDrawContent=false;
	private Paint p1=new Paint();
	private Paint p2=new Paint();
	Paint textPaint=new Paint();
	HtmlBrowser htmlBrowser;
	boolean textMode=true;
	HtmlIndentEditor indentEditor;
	TabData.HtmlBrowserInfo ni;
	Rect layoutSaved=new Rect();
	int i1,i2;
	static int defaultTextColor=0xffff00ff;
	boolean canSave;
	MainActivity ma;
	HtmlEditorTab(MainActivity ma){
		super(ma);
		this.ma=ma;
		setTypeface(Typeface.MONOSPACE);
        setTextSize(TypedValue.COMPLEX_UNIT_DIP,12);
		setTextColor(defaultTextColor);
		setGravity(Gravity.CENTER);
		setFocusable(false);
		p1.setColor(0xff444444);
		p1.setStrokeCap(Paint.Cap.SQUARE);
		p1.setStrokeWidth((int)(6*getResources().getDisplayMetrics().density));
		p2.setColor(0xff00bbff);
		p2.setStyle(Paint.Style.FILL);
		setTypeface(Typeface.MONOSPACE);
        setTextSize(TypedValue.COMPLEX_UNIT_DIP,12);
		StateListDrawable stat=new StateListDrawable();
		stat.addState(new int[]{android.R.attr.state_selected},new ColorDrawable(0x55777777));
		setBackground(stat);
		indentEditor=new HtmlIndentEditor(ma);
		htmlBrowser=new HtmlBrowser(ma);
	}
	public void setOnClickListener(View.OnClickListener l) {
		ocl=l;
	}
	public void setOnLongClickListener(View.OnLongClickListener l) {
		olcl=l;
	}
	boolean needRemember=true;
	@Override
	public boolean isNeedRemember() {
		return needRemember;
	}
	boolean underline;
	@Override
	public void letUnderline(boolean b) {
		underline=b;
		invalidate();
	}
	@Override
    public void setTextColor(int color) {
        super.setTextColor(color);
        i2=color;
    }
	@Override
	public void draw(Canvas canvas){
        textPaint.setTextSize(getTextSize());
        textPaint.setColor(i2);
        textPaint.setTypeface(getTypeface());
		canvas.drawRect(getWidth()-3,i1,getWidth(),getHeight()-i1,p1);
		if(!dontDrawContent){
			drawContent(canvas);
		}
	}
	@Override
	public void drawShadow(Canvas c){
		c.drawColor(0xff888888);
		drawContent(c);
	}
	void drawContent(Canvas c){
		CharSequence cs=getText();
        float[] ws=new float[cs.length()];
        int count=textPaint.getTextWidths(getText().toString(),ws);
        int i;
        float wa1=0;
        for(i=count-1;i>=0;i--){
            wa1+=ws[i];
            if(wa1>getWidth()){
                break;
            }
        }
        String truncated=cs.toString().substring(i+1);
        int textx=(getWidth()-(int)textPaint.measureText(truncated))/2;
        Paint.FontMetricsInt pfi=textPaint.getFontMetricsInt();
        int texty=(pfi.descent-pfi.ascent)/2+getHeight()/2-i1/2;
        c.drawText(truncated,textx,texty,textPaint);
		if(getText().toString().isEmpty()){
			int pl,pt,pr,pb;
			pt=getHeight()/4;
			pl=(getWidth()-getHeight())/2+pt;
			pr=getWidth()-pl;
			pb=getHeight()-pt;
			c.drawLine(getWidth()/2,pt,getWidth()/2,pb,p1);
			c.drawLine(pl,getHeight()/2,pr,getHeight()/2,p1);
		}else if(underline){
			c.drawRect(0,getHeight()-5,getWidth(),getHeight(),p2);
		}
	}
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        i1=getMeasuredHeight()/5;  
	}
	Point touchDownRaw=new Point();
	long touchDownTime=-100;
	int touchDownCount=0;
    Point touch_move=new Point();
    int touchMovedFarthest;
	int dy,dx,dyAbs,dxAbs;
	int touchCtrl;
	WaitLongClick wlc;
	boolean touchMoved;
	volatile boolean longClicked=false;
	public boolean onTouchEvent(MotionEvent event) {
		int rx=(int)event.getRawX();
		int ry=(int)event.getRawY();
        TabBar.Shadow sh=ma.gui.tabs.sh;
        switch(event.getAction()){
            case MotionEvent.ACTION_DOWN:
                getGlobalVisibleRect(layoutSaved);
				touchMoved=false;
				longClicked=false;
                touchDownRaw.x=rx;
                touchDownRaw.y=ry;
				touchMovedFarthest=0;
				ma.gui.hsv.requestDisallowInterceptTouchEvent(true);
				if(touchDownCount==0){
					touchDownTime=System.currentTimeMillis();
					touchDownCount=1;
					if(ni==null){
						touchCtrl=4;
					}else{
						touchCtrl=2;
					}
					if(wlc==null){
						//log.alert("error,wlc==null");
						wlc=new WaitLongClick();
						wlc.start();
					}else{
						wlc.interrupt();
					}
				}else if(touchDownCount==1){
					int gap=(int)(System.currentTimeMillis()-touchDownTime);
					touchDownTime=System.currentTimeMillis();
					//touch_downCount=0;
					if(gap<300){
						touchCtrl=1;//move the view
                        Rect rect=new Rect();
                        sh.getGlobalVisibleRect(rect);
                        sh.wlp.x=rect.left;
                        sh.wlp.y=rect.top;
                        sh.wlp.width=rect.width();
                        sh.wlp.height=rect.height();
                        sh.target=this;
                        ma.wm.addView(sh,sh.wlp);
						dontDrawContent=true;
						invalidate();
					}else{
						if(ni==null){
							touchCtrl=4;
						}else{
							touchCtrl=2;
						}
						if(wlc==null){
							//log.alert("error,wlc==null");
							wlc=new WaitLongClick();
							wlc.start();
						}else{
							wlc.interrupt();
							wlc=new WaitLongClick();
							wlc.start();
						}
					}
				}
                break;
            case MotionEvent.ACTION_MOVE:
                dy=ry-touchDownRaw.y;
				dx=rx-touchDownRaw.x;
				dyAbs=Math.abs(dy);
				dxAbs=Math.abs(dx);
				if(dyAbs>5||dxAbs>5){
					touchMoved=true;
					if(wlc!=null){
						if(!wlc.interrupted())wlc.interrupt();
					}
				}
				switch(touchCtrl){
					case 1:
						int shadowx=layoutSaved.left+dx;
                        int shadowy=layoutSaved.top+dy;
                        sh.wlp.x=shadowx;
                        if(shadowy<=layoutSaved.top){
                            sh.wlp.y=shadowy;
                            dontDrawContent=true;
                        }else if(shadowy>=layoutSaved.bottom){
                            sh.wlp.y=layoutSaved.bottom;
                            dontDrawContent=false;
                            invalidate();
                            int cx=shadowx+layoutSaved.width()/2;
                            int cen=ma.wp/2;
                            if(cx<cen){
                                sh.wlp.x=0;
                            }else{
                                sh.wlp.x=ma.wp-sh.wlp.width;
                            }
                            ma.wm.updateViewLayout(sh,sh.wlp);
                            return true;
                        }else{
                            sh.wlp.y=shadowy;
                            dontDrawContent=true;
                        }
						int cx=shadowx+layoutSaved.width()/2;
						outmost:
						for(int i=0,lim=ma.gui.tabs.getChildCount();true;i++){
							if(i<lim){
								View child=ma.gui.tabs.getChildAt(i);
								if(cx>=child.getLeft()&&cx<child.getRight()){
									if(child==this){
										ma.gui.tabs.invalidate();
										//ma.gui.requestLayout();
										break;
									}else{
										ma.gui.tabs.removeView(this);
										ma.gui.tabs.addView(this,i);
										//ma.gui.tabs.requestLayout();
										break;
									}
								}else if(child==this){
									for(i++;true;i++){
										if(i<lim){
											child=ma.gui.tabs.getChildAt(i);
											if(cx>=child.getLeft()&&cx<child.getRight()){
												ma.gui.tabs.removeView(this);
												ma.gui.tabs.addView(this,i);
												//ma.gui.tabs.requestLayout();
												break outmost;
											}
										}else{
											ma.gui.tabs.invalidate();
											break outmost;
										}
									}
								}
							}else{
								ma.gui.tabs.invalidate();
								break;
							}
						}
						break;
					case 2://手指向下拽动控件
						if(touchMoved){
							if(dyAbs>dxAbs){
								touchCtrl=3;//log.alert("slip");
								if(wlc!=null)wlc.interrupt();
								if(dy>0){
									setScrollY(-dy);
									layout(layoutSaved.left,layoutSaved.top+dy,layoutSaved.right,layoutSaved.bottom+dy);
								}else{
									setScrollY(0);
									layout(layoutSaved.left,layoutSaved.top,layoutSaved.right,layoutSaved.bottom);
								}
								getParent().requestLayout();
								//invalidate();
								return true;
							}else{
								ma.gui.hsv.requestDisallowInterceptTouchEvent(false);
								touchCtrl=4;
								return false;
							}
						}else{
							getParent().getParent().requestDisallowInterceptTouchEvent(true);
						}
						break;
					case 3:
						getParent().getParent().requestDisallowInterceptTouchEvent(true);
						if(dy>0){
							setScrollY(-dy);
							layout(layoutSaved.left,layoutSaved.top+dy,layoutSaved.right,layoutSaved.bottom+dy);
						}else{
							setScrollY(0);
							layout(layoutSaved.left,layoutSaved.top,layoutSaved.right,layoutSaved.bottom);
						}
						getParent().requestLayout();
						//invalidate();
						return true;
					case 4:
						break;
				}
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
				//log.alert("up");
				if(wlc!=null){
					wlc.interrupt();
				}
				if(touchCtrl==3){
					//log.alert("sliped");
					dy=ry-touchDownRaw.y;
					getParent().requestLayout();
					setScrollY(0);
					if(dy>getHeight()){
						ma.gui.onTabSlipped(this);
					}
					invalidate();
				}else if(touchCtrl==2){
					setScrollY(0);
					if(!longClicked&&!touchMoved){
						if(ocl!=null){
							ocl.onClick(this);
						}
					}
					invalidate();
				}else if(touchCtrl==4){
					setScrollY(0);
					invalidate();
					if(!longClicked&&!touchMoved){
						if(ocl!=null){
							ocl.onClick(this);
						}
					}
				}else if(touchCtrl==1){//保存tabs中当前TabFab的顺序
					dontDrawContent=false;
                    if(sh.isAttachedToWindow())ma.wm.removeView(sh);
					invalidate();
                    int cx=layoutSaved.left+dx+layoutSaved.width()/2;
                    int cen=ma.wp/2;
                    if(cx<cen){
                        ma.gui.tabs.removeView(this);
                        ma.gui.tabs.addView(this,0);
                    }else{
                        ma.gui.tabs.removeView(this);
                        ma.gui.tabs.addView(this,ma.gui.tabs.getChildCount());
                    }
                    ma.gui.saveAllTab();
				}else{
					getParent().requestLayout();
				}
				break;
            case MotionEvent.ACTION_CANCEL:
				invalidate();
				if(sh.isAttachedToWindow())ma.wm.removeView(sh);
				if(touchCtrl==1){
					//Toast.makeText(ma,"23333",0).show();
					dontDrawContent=false;
					invalidate();
				}else{
				}
        }
        return true;
    }
	class WaitLongClick extends Thread {
		@Override
		public void run() {
			super.run();
			try{
				sleep(TabBar.clickLimit);
				longClicked=true;
				if(olcl!=null){
					post(new Runnable(){
						public void run(){
							olcl.onLongClick(HtmlEditorTab.this);
						}
					});
				}
			}catch(Exception e){
			}
		}
	}
}
